package com.example.administrator.im.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.NetUtils;
import com.example.administrator.im.Contents;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements Handler.Callback {

    @Bind(R.id.list_view)
    ListView listView;

    private List<String> list = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private MyApplication application;
    private NewMessageBroadcastReceiver msgReceiver;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        application = (MyApplication) getApplication();

        handler = new Handler(Looper.myLooper(), this);
        //注册一个监听连接状态的listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        //新消息监听
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter filter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        filter.setPriority(3);
        registerReceiver(msgReceiver, filter);
        //已读小消息监听回调
        EMChatManager.getInstance().getChatOptions().setRequireAck(false);
        //如果用到已读的回执需要把这个flag设置成true
        IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        //监听联系人的变化
        EMContactManager.getInstance().setContactListener(new MyContactListener());

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ChatActivity.class);
                intent.putExtra("username", adapter.getItem(position));
                startActivityForResult(intent,22);
            }
        });

        //最后要通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
        EMChat.getInstance().setAppInited();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(null != data && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String string = bundle.getString(ChatActivity.DELETED);
            Message message = handler.obtainMessage();
            message.what = 2;
            message.obj = string;
            handler.sendMessage(message);
        }
    }

    @OnClick({R.id.add_friends, R.id.tv_apply_noty})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_friends:
                startActivity(new Intent(this, AddFriendsActivity.class));
                break;
            case R.id.tv_apply_noty:
                startActivity(new Intent(this, ApplyAndNotificationActivity.class));
                break;
        }
    }

    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            String s = usernameList.get(0);
            Message message = handler.obtainMessage();
            message.what = 0;
            message.obj = s;
            handler.sendMessage(message);
        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            Message message = handler.obtainMessage();
            message.what = 1;
            message.obj = usernameList;
            handler.sendMessage(message);
        }

        @Override
        public void onContactInvited(String username, String reason) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不要重复提醒
            Map<String, Object> map = new HashMap<>();
            map.put("add_username", username);
            map.put("add_reason", reason);
            Contents.lists.add(map);
        }

        @Override
        public void onContactAgreed(String username) {
            //同意好友请求
            Log.i("FFF", "同意" + username);
        }

        @Override
        public void onContactRefused(String username) {
            // 拒绝好友请求
            Log.i("FFF", "拒绝" + username);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        //获取好友列表
        getFriendsList();
    }

    private void getFriendsList() {
        new GetFriedsListThread().start();
    }

    @Override
    public boolean handleMessage(Message msg) {

        if (msg.what == 0 && null != msg.obj) {
            String newAdd = (String) msg.obj;
            if (!list.contains(newAdd)) {
                list.add(newAdd);
                adapter.notifyDataSetChanged();
            }
        }
        if(msg.what == 1 && null != msg.obj) {
            List<String> usernames = (List<String>) msg.obj;
            for (int i = 0; i < usernames.size(); i++) {
                String username = usernames.get(i);
                if(list.contains(username)) {
                    list.remove(username);
                    adapter.notifyDataSetChanged();
                }
            }
        }
        if(msg.what == 2 && null != msg.obj) {
            String s = (String) msg.obj;
            if(list.contains(s)) {
                list.remove(s);
                adapter.notifyDataSetChanged();
            }
        }
        return false;
    }

    public class GetFriedsListThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                final List<String> userNames = EMContactManager.getInstance().getContactUserNames();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (userNames.size() > 0) {
                            list.clear();
                            list.addAll(userNames);
                            adapter.notifyDataSetChanged();
                        }
                    }
                });
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(ackMessageReceiver);
        unregisterReceiver(msgReceiver);
    }

    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 注销广播
            abortBroadcast();

            // 消息id（每条消息都会生成唯一的一个id，目前是SDK生成）
            String msgId = intent.getStringExtra("msgid");
            //发送方
            String username = intent.getStringExtra("from");
            // 收到这个广播的时候，message已经在db和内存里了，可以通过id获取mesage对象
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);
            Log.i("CHAT", "接收到的消息" + message.toString());
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            // 如果是群聊消息，获取到group id
            if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                username = message.getTo();
            }
            if (!username.equals(username)) {
                // 消息不是发给当前会话，return
                return;
            }
        }
    }

    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");
            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);
                if (msg != null) {
                    msg.isAcked = true;
                }
            }

        }
    };

    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        Toast.makeText(getApplicationContext(), "帐号已经被移除", Toast.LENGTH_SHORT).show();
                    } else if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆
                        Toast.makeText(getApplicationContext(), "帐号在其他设备登陆", Toast.LENGTH_SHORT).show();
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) ;
                            //连接不到聊天服务器
                        else {
                            //当前网络不可用，请检查网络设置
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        logout();
    }

    private void logout() {
        Contents.lists.clear();
        //此方法为异步方法
        EMChatManager.getInstance().logout(new EMCallBack() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                Log.i("CHAT", "退出成功");
            }

            @Override
            public void onProgress(int progress, String status) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int code, String message) {
                // TODO Auto-generated method stub

            }
        });
    }
}
